<template>
  <div class="base-content">
    <div class="basic-info">
      <el-form ref="queryForm" :model="queryForm" :rules="queryFormRule">
        <el-row>
          <el-form-item
            label="检测项目"
            prop="detectionItemIdList"
            :label-width="formLabelWidth"
          >
            <el-col :span="2">
              <el-button
                type="primary"
                style="width: 90%"
                @click="choiceDetectionItem"
                >选择</el-button
              >
            </el-col>
            <el-col :span="15">
              <el-input
                v-model="queryForm.detectionItemName"
                disabled
              ></el-input>
            </el-col>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            label="开展时间"
            prop="curtainTimeList"
            :label-width="formLabelWidth"
          >
            <el-col :span="10">
              <el-date-picker
                v-model="queryForm.curtainTimeList"
                type="datetimerange"
                align="left"
                :picker-options="expireTimeOption"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              ></el-date-picker>
            </el-col>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            label="检测人"
            prop="testerIdList"
            :label-width="formLabelWidth"
          >
            <el-col :span="10">
              <el-select
                ref="selectDom"
                v-model="queryForm.testerIdList"
                style="width: 100%"
                :multiple="true"
                :placeholder="'请选择检测人'"
                filterable
                remote
                reserve-keyword
                :remote-method="remoteUser"
                value-key="id"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-col>
          </el-form-item>
        </el-row>
      </el-form>

      <div class="base-content-operate">
        <el-button type="primary" @click="getList">生成报表</el-button>
        <el-button @click="cancelForm">重置</el-button>
        <el-button icon="el-icon-download" type="primary" @click="Export"
          >导出</el-button
        >
      </div>

      <el-table
        :data="list"
        element-loading-text="Loading"
        fit
        highlight-current-row
      >
        <el-table-column label="检测项目" prop="detectionItemName" />
        <el-table-column label="检测人" prop="testName" />
        <el-table-column label="开展时间" prop="curtainTime">
          <template slot-scope="scope">
            {{ formatTime(scope.row.curtainTime) }}
          </template>
        </el-table-column>
        <el-table-column label="样品编号" prop="sampleNum" />
        <el-table-column label="样品名称" prop="sampleName" />
        <el-table-column label="样品类别" prop="sampleCategory" />
        <el-table-column label="检验类别" prop="testCategory" />
        <el-table-column label="实验记录单号" prop="experimentNumber" />
        <el-table-column label="检验结果" prop="testResult" />
      </el-table>

      <BasePagination
        :total="pagination.total"
        :current-page="pagination.pageIndex"
        :page-count="pagination.total"
        @changePage="changePage"
        @sizeChange="sizeChange"
      />
      <ChoiceDetectionItemDialog
        ref="ChoiceDetectionItemDialog"
        v-model="dialogDetectionItem"
        :generate-button-state="false"
        :same-sample-category="false"
        @DetectionItemClose="detectionItemClose"
      />
    </div>
  </div>
</template>

<script>
import { getUserListNoPage } from "../../../api/Permission/user.js";
import { getList } from "../../../api/Eln/ElnTestResultStatistics.js";
import {
  formatTime,
  formatSubtractTime,
  formatTimeMax,
} from "../../../utils/time";
import { export_json_to_excel } from "@/vendor/Export2Excel";

export default {
  name: "ElnTestResultStatisticsList",
  components: {},
  props: {},
  data() {
    return {
      dialogDetectionItem: false,
      formLabelWidth: "90px",
      list: [],
      userList: [],
      formatTime,
      formatSubtractTime,
      formatTimeMax,
      tHeader: [
        "检测项目",
        "检测人",
        "开展时间",
        "样品编号",
        "样品名称",
        "样品类别",
        "检验类别",
        "实验记录单号",
        "检验结果",
      ],
      filterVal: [
        "detectionItemName",
        "testName",
        "curtainTime",
        "sampleNum",
        "sampleName",
        "sampleCategory",
        "testCategory",
        "experimentNumber",
        "testResult",
      ],
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
      queryFormRule: {
        // detectionItemIdList: [
        //   {
        //     required: true,
        //     trigger: "blur",
        //     message: "请选择检测项目",
        //   },
        // ],
        curtainTimeList: [
          {
            required: true,
            trigger: "blur",
            message: "请选择开展时间",
          },
        ],
      },
      expireTimeOption: {
        selectableRange: "00:00:00 - 23:59:59",
      },
      queryForm: {
        detectionItemIdList: [],
        detectionItemName: "",
        curtainTimeList: [],
        tableDetectionItemAll: [],
        testerIdList: [],
      },
    };
  },
  created() {
    var stateDate = this.formatSubtractTime(30) + " 00:00:00";
    var endDate = this.formatTimeMax();
    this.queryForm.curtainTimeList = [stateDate, endDate];
    this.remoteUser();
  },
  methods: {
    export_json_to_excel,
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          return v[j];
        })
      );
    },
    Export() {
      getList(this.queryForm, this.pagination)
        .then((res) => {
          for (var i = 0; i < res.data.dataList.length; i++) {
            res.data.dataList[i].curtainTime = this.formatTime(
              res.data.dataList[i].curtainTime
            );
          }
          var data = this.formatJson(this.filterVal, res.data.dataList);
          export_json_to_excel({
            header: this.tHeader, // 表头
            data, // 数据
            filename: "检验结果统计", // 导出文件名
            autoWidth: true, // 导出宽度自动
            bookType: "xlsx", // 导出后缀
          });
        })
        .catch(() => { });
    },

    cancelForm() {
      this.$refs.queryForm.resetFields();
      this.queryForm.detectionItemIdList = [];
      this.queryForm.detectionItemName = "";
      this.queryForm.curtainTimeList = [];
      this.queryForm.tableDetectionItemAll = [];
      this.queryForm.testerIdList = [];
      this.list = [];
      this.pagination.total = 0;
      this.pagination.pageIndex = 1;
    },
    // 搜索人员
    getUser(name = "") {
      return new Promise((resolve) => {
        getUserListNoPage({ name }).then((res) => {
          resolve(res);
        });
      });
    },
    async remoteUser(query) {
      this.searchUserLoading = true;
      const filter = await this.getUser(query);
      if (filter && filter.data && filter.data.length) {
        this.userList = filter.data;
      }
      this.searchUserLoading = false;
    },
    detectionItemClose(data) {
      this.queryForm.detectionItemIdList = [];
      for (let i = 0; i < data.length; i++) {
        for (let o = 0; o < data[i].detectionItemData.length; o++) {
          this.queryForm.detectionItemIdList.push(
            data[i].detectionItemData[o].id
          );
          if (
            data[i].detectionItemData[o].sysBusinessDetectionItemSonList !==
            undefined &&
            data[i].detectionItemData[o].sysBusinessDetectionItemSonList !==
            null
          ) {
            for (
              let p = 0;
              p <
              data[i].detectionItemData[o].sysBusinessDetectionItemSonList
                .length;
              p++
            ) {
              this.queryForm.detectionItemIdList.push(
                data[i].detectionItemData[o].sysBusinessDetectionItemSonList[p]
                  .id
              );
            }
          }
        }
      }
      this.queryForm.detectionItemName = data
        .map((item) => item.detectionItemName)
        .join(", ");

      this.queryForm.tableDetectionItemAll = data;
    },
    // 选择检测项目
    choiceDetectionItem() {
      var data = [].concat(
        ...this.queryForm.tableDetectionItemAll.map(
          (item) => item.detectionItemData
        )
      );

      this.$refs.ChoiceDetectionItemDialog.sampleDeteciontItemData =
        this.queryForm.tableDetectionItemAll;

      // 选择的检测项目表赋值检测项目
      this.$refs.ChoiceDetectionItemDialog.selectedTableData = JSON.parse(
        JSON.stringify(data)
      );

      this.dialogDetectionItem = true;
    },
    changePage(val) {
      this.pagination.pageIndex = val;
      this.getList();
    },
    sizeChange(val) {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
      this.getList();
    },
    getList() {
      this.$refs.queryForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          getList(this.queryForm, this.pagination)
            .then((res) => {
              this.list = res.data.dataList ? res.data.dataList : [];
              this.pagination.total = res.data.total;
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        }
      });
    },
  },
};
</script>
